package com.gzx.plugin.tjzy.modular.word.mediation.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fhs.trans.service.impl.TransService;
import com.gzx.plugin.tjzy.modular.bank.entity.GzxBankInfo;
import com.gzx.plugin.tjzy.modular.bank.service.GzxBankInfoService;
import com.gzx.plugin.tjzy.modular.bank.vo.GzxBankInfoVo;
import com.gzx.plugin.tjzy.modular.file.consts.GzxFileBucketConstant;
import com.gzx.plugin.tjzy.modular.file.service.FileService;
import com.gzx.plugin.tjzy.modular.word.mediation.bo.GzxWordMediationAddBo;
import com.gzx.plugin.tjzy.modular.word.mediation.bo.GzxWordMediationQueryBo;
import com.gzx.plugin.tjzy.modular.word.mediation.consts.GzxWordMediationConstant;
import com.gzx.plugin.tjzy.modular.word.mediation.entity.GzxWordMediation;
import com.gzx.plugin.tjzy.modular.word.mediation.mapper.GzxWordMediationMapper;
import com.gzx.plugin.tjzy.modular.word.mediation.service.GzxWordMediationService;
import com.gzx.plugin.tjzy.modular.word.mediation.vo.GzxWordMediationVo;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.stereotype.Service;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.common.util.CommonDateUtil;
import vip.xiaonuo.common.util.CommonDownloadUtil;
import vip.xiaonuo.common.util.MapstructUtils;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zjt
 * @description
 * @date 2025/3/4 16:15
 */
@Slf4j
@DS("tjzy")
@Service
@RequiredArgsConstructor
public class GzxWordMediationServiceImpl implements GzxWordMediationService {

    private final GzxWordMediationMapper mediationWordMapper;

    private final TransService transService;

    private final GzxBankInfoService bankInfoService;

    private final FileService fileService;

    /**
     * 分页查询
     *
     * @param mediationWordQueryBo
     * @return
     */
    @Override
    public Page<GzxWordMediationVo> pageList(GzxWordMediationQueryBo mediationWordQueryBo) {
        LambdaQueryWrapper<GzxWordMediation> lambdaQueryWrapper = Wrappers.<GzxWordMediation>lambdaQuery()
                .eq(StringUtils.isNoneBlank(mediationWordQueryBo.getDeptId()), GzxWordMediation::getCreateDept, mediationWordQueryBo.getDeptId())
                .orderByDesc(GzxWordMediation::getId);
        List<String> roleCodeList = StpLoginUserUtil.getLoginUser().getRoleCodeList();
        boolean isAdmin = roleCodeList.contains("superAdmin") || roleCodeList.contains("itAdmin") || roleCodeList.contains("branchManager");
        if (!isAdmin) {
            lambdaQueryWrapper.eq(GzxWordMediation::getCreateUser, StpLoginUserUtil.getLoginUser().getId());
        }
        Page<GzxWordMediationVo> page = mediationWordMapper.selectVoPage(new Page<>(mediationWordQueryBo.getCurrent(), mediationWordQueryBo.getSize()), lambdaQueryWrapper);
        page.getRecords().forEach(s -> {
            s.setNoSensitiveDebtorPhone(s.getDebtorPhone());
            s.setNoSensitiveDebtorCardId(s.getDebtorCardId());
        });
        return page;
    }

    /**
     * 新增调解协议
     *
     * @param mediationWordAddBo
     */
    @Override
    public String addOrEdit(GzxWordMediationAddBo mediationWordAddBo) {
        GzxWordMediation wordMediation = MapstructUtils.convert(mediationWordAddBo, GzxWordMediation.class);
        if (mediationWordAddBo.getId() == null) {
            wordMediation.setCreateDept(StpLoginUserUtil.getLoginUser().getOrgId());
            mediationWordMapper.insert(wordMediation);
        } else {
            mediationWordMapper.updateById(wordMediation);
        }
        return String.valueOf(wordMediation.getId());
    }

    /**
     * 设置身份证号
     *
     * @param id
     * @param debtorCardId
     */
    @Override
    public void saveDebtorCard(Long id, String debtorCardId) {
        GzxWordMediation wordMediation = new GzxWordMediation();
        wordMediation.setId(id);
        wordMediation.setDebtorCardId(debtorCardId);
        mediationWordMapper.updateById(wordMediation);
    }

    /**
     * 生成调解协议
     *
     * @param mediationId
     * @throws IOException
     */
    @Override
    public void generateMediationWord(Long mediationId, HttpServletResponse response) throws IOException {
        // 查询到的数据
        GzxWordMediationVo mediationWordVo = mediationWordMapper.selectVoById(mediationId);
        transService.transOne(mediationWordVo);
        Map<String, Object> mediationWordMap = getDataMap(mediationWordVo);
        File ossFile = fileService.download(GzxFileBucketConstant.EXCEL_TEMPLATE, mediationWordVo.getTemplateName());
        try (InputStream templateInputStream = new FileInputStream(ossFile);
             XWPFDocument document = new XWPFDocument(templateInputStream)) {
            //替换主文档
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                replaceTextInParagraph(paragraph, mediationWordMap);
            }
            File tempFile = null;
            try {
                // 创建临时文件并保存修改后的文档
                tempFile = File.createTempFile(mediationWordVo.getDebtorName() + "_调解协议", ".docx");
                try (FileOutputStream fos = new FileOutputStream(tempFile)) {
                    document.write(fos); // 将修改后的文档写入临时文件
                }
                // 下载文件（无需保留临时文件）
                CommonDownloadUtil.download(tempFile, response);
            } catch (Exception e) {
                log.error("生成调解协议失败", e);
            } finally {
                if (tempFile != null) {
                    tempFile.deleteOnExit();
                }
            }
        }
    }

    /**
     * 获取调解协议数据
     *
     * @param caseId
     * @return
     */
    @Override
    public GzxWordMediationVo getWordMediationData(Long caseId) {
        return null;
    }

    private Map<String, Object> getDataMap(GzxWordMediationVo mediationWordVo) {
        Map<String, Object> mediationWordMap = JSON.parseObject(JSON.toJSONString(mediationWordVo), HashMap.class);
        //拆解年月日
        String[] contractStartDate = mediationWordVo.getContractStartDate().split("-");
        mediationWordMap.put("contractStartYear", contractStartDate[0]);
        mediationWordMap.put("contractStartMonth", contractStartDate[1]);
        mediationWordMap.put("contractStartDay", contractStartDate[2]);
        mediationWordMap.put("currentDate", CommonDateUtil.getTodayStrText()); // 添加当前日期
        // 解析 detailJson 为数组，生成分期数据
        getRepaymentDetail((String) mediationWordMap.get("detailJson"), mediationWordMap);
        //设置银行账户信息
        getBankContent(mediationWordVo.getBankCode(), mediationWordMap);
        return mediationWordMap;
    }

    private void getRepaymentDetail(String detailJson, Map<String, Object> mediationWordMap) {
        JSONArray detailJsonArray = JSON.parseArray(detailJson);
        String contentText = GzxWordMediationConstant.DETAIL_CONTENT;
        StringBuilder detailContent = new StringBuilder();
        for (int i = 0; i < detailJsonArray.size(); i++) {
            Map<String, Object> detailMap = JSON.parseObject(detailJsonArray.getString(i), HashMap.class);
            detailContent.append(contentText.replace("${detailDate}", detailMap.get("detailDate").toString()).replace("${detailAmount}", detailMap.get("detailAmount").toString()));
        }
        mediationWordMap.put("detailContent", detailContent.toString());
    }

    private void getBankContent(String bankCode, Map<String, Object> mediationWordMap) {
        if (StringUtils.isNotBlank(bankCode)) {
            String[] backCode = bankCode.split(",");
            //查询银行信息
            List<GzxBankInfoVo> bankInfoVoList = bankInfoService.listAll(Wrappers.<GzxBankInfo>lambdaQuery().in(GzxBankInfo::getCode, backCode));
            if (CollectionUtil.isNotEmpty(bankInfoVoList)) {
                StringBuilder bankContent = new StringBuilder();
                for (GzxBankInfoVo bankInfoVo : bankInfoVoList) {
                    bankContent.append(GzxWordMediationConstant.BANK_ACCOUNT_NAME_CONTENT.replace("${accountName}", bankInfoVo.getAccountName()));
                    bankContent.append(GzxWordMediationConstant.BANK_BANK_NAME_CONTENT.replace("${bankName}", bankInfoVo.getBankName()));
                    bankContent.append(GzxWordMediationConstant.BANK_BANK_ACCOUNT_CONTENT.replace("${bankAccount}", bankInfoVo.getBankAccount()));
                    bankContent.append("\r");
                }
                mediationWordMap.put("bankInfo", bankContent);
            }
        }
    }

    private void replaceTextInParagraph(XWPFParagraph paragraph, Map<String, Object> replacements) {
        // 获取整个段落的文本
        String paragraphText = paragraph.getText();
        // 替换占位符
        for (Map.Entry<String, Object> entry : replacements.entrySet()) {
            if (paragraphText.contains(entry.getKey())) {
                paragraphText = paragraphText.replace("${" + entry.getKey() + "}", String.valueOf(entry.getValue()));
            }
        }
        // 清空原有的 Runs
        List<XWPFRun> runs = paragraph.getRuns();
        for (int i = runs.size() - 1; i >= 0; i--) {
            paragraph.removeRun(i);
        }
        // 添加新的 Run 并设置替换后的文本
        XWPFRun newRun = paragraph.createRun();
        newRun.setText(paragraphText);
    }
}
